<template>
    <div>
        <div class="padding-tb">
            <el-input style="width: 150px;" v-model="searchConditions.key" size="mini" placeholder="活动名称"></el-input>
            <el-date-picker
                v-model="searchConditions.dateRange"
                type="daterange"
                :picker-options="raidDateOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                align="right">
            </el-date-picker>
            <el-button type="primary" size="mini" @click="fetchData()">搜索</el-button>
            <el-button type="primary" size="mini" v-if="isLogin && level>1" @click="showImportForm()">导入Raid数据</el-button>
            <el-tooltip content="将数据保存为文件，否则当服务器重启时数据会丢失。请在全部操作完成后再使用此功能" placement="top" effect="light">
              <el-button type="danger" size="mini" v-if="isLogin && level>1" slot="" @click="saveToFile">保存数据到文件</el-button>
            </el-tooltip>
        </div>
        <div>
            <el-table :data="tableData.list" border stripe style="width: 100%">
                <el-table-column prop="key" align="center" label="活动名称" width="180">
                    <template slot-scope="scope">
                        <el-tooltip content="查看活动详情" placement="top" effect="light">
                          <el-button type="text" size="mini" @click="viewDetail(scope.row.key)">{{scope.row.key}}</el-button>
                        </el-tooltip>
                        <el-button type="primary" size="mini" @click="viewDetail(scope.row.key)">查看</el-button>
                        <el-tooltip content="首次击杀BOSS" placement="right" effect="light">
                        <div class="first-down-label" v-if="scope.row.hasFirstDown">FD</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="zone" align="center" label="副本/地区" width="140"></el-table-column>
                <el-table-column prop="start" label="开始时间" align="center" width="200"></el-table-column>
                <el-table-column prop="end" label="结束时间" align="center" width="180"></el-table-column>
                <el-table-column prop="end" label="参加人员" align="center">
                    <template slot-scope="scope">
                        <div class="name-wrapper">
                            <span class="name-label" v-for="p in scope.row.players" :key="p.name" :style="{color: classMap[p.class]}">{{p.name}}</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="padding-tb">
            <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageNoChange"
            :current-page="searchConditions.pageNo"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="searchConditions.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.total">
            </el-pagination>
        </div>

        <el-dialog :title="`活动【${raid.key}】的详细记录`" width="900px" :visible.sync="raidShow">
          <div>
            <el-radio-group v-model="mode" size="mini">
              <el-radio-button label="normal">总览模式</el-radio-button>
              <el-radio-button label="timeline">时间轴模式</el-radio-button>
            </el-radio-group>
            <component 
              :is="mode=='normal'?'RaidDetailNormal':'RaidDetailTimeLine'"
              :raid="mode=='normal'?raidSource:raid"
              ></component>
          </div>
        </el-dialog>

        <el-dialog title="导入Raid数据" width="1100px" 
          :visible.sync="importFormShow" 
          :before-close="confirmClose"
          :fullscreen="true"
          :opened="clearFiles"
          class="import-dialog"
          >
          <div class="padding-tb">
            <el-radio v-model="charset" label="gbk">国标码(一般人请选这个)</el-radio>
            <el-radio v-model="charset" label="utf8">UTF8编码(专业人士用这个)</el-radio>
            <el-radio v-model="charset" label="source">使用源文件导入(非特殊情况不要用)</el-radio>
          </div>
          <el-upload
            class="upload-demo"
            ref="upload"
            :limit="1"
            :data="{charset: charset}"
            :headers="{Authorization: token}"
            action="/api/manage/parseRaidXml"
            :with-credentials="true"
            :show-file-list="true"
            :on-success="uploadSuccess"
            :auto-upload="true">
            <el-button slot="trigger" size="small" type="primary">请选择由CT_RaidTracker插件导出的数据文件</el-button>
          </el-upload>
          <el-alert
            v-if="!parsingCompleted"
            show-icon
            :closable="false"
            title="注意：选择完文件之后就会自动添加新入团的号"
            description="如果有新入团的小号，请先选择文件，然后关闭对话框，在DKP管理界面建立小号关联，否则可能无法正确按小号规则扣分"
            type="warning">
          </el-alert>
          <div class="padding-tb" v-if="parsingCompleted">
            <el-radio-group v-model="scoreType" size="mini">
              <el-radio-button 
                v-for="(v, i) of ['TAQ', 'NAXX', 'TAQ2', 'NAXX2']"
                :key="i"
                :disabled="i<2"
              :label="v">使用{{v}}的分数</el-radio-button>
            </el-radio-group>
            <el-radio-group v-model="dkpMode" size="mini">
              <el-radio-button label="byBoss">按Boss算分</el-radio-button>
              <el-radio-button label="byItem">按装备算分</el-radio-button>
            </el-radio-group>
          </div>
          <!-- <el-input v-model.lazy="dkpStr" :validate-event="false" placeholder="请复制从CT_RaidTracker插件导出的字符串到这里">
            <template slot="prepend">导入字符串</template>
            <template slot="append">
              <el-button type="primary" size="mini" @click="importData()">导入</el-button>
            </template>
          </el-input> -->
          <div class="raid-info-area" v-if="parsingCompleted">
            <el-form size="mini" :label-width="formLabelWidth" inline>
              <el-form-item label="名称"><span class="underline">{{dkpParsed.key}}</span></el-form-item>
              <el-form-item label="区域"><span class="underline">{{dkpParsed.zone}}</span></el-form-item>
              <el-form-item label="开始时间"><span class="underline">{{dkpParsed.start}}</span></el-form-item>
              <el-form-item label="结束时间"><span class="underline">{{dkpParsed.end}}</span></el-form-item>
            </el-form>
            <div class="collapse-title-wrapper">
                <el-tooltip placement="right" effect="light">
                    <div slot="content">
                        加分时，如果大小号都在团，则只有大号可以加分<br/>
                        如果大号不在团，小号的分数将自动加到大号上<br/>
                        如果有多个小号在团，并且大号没在团，<br/>
                        将只有后一个小号可以设置分数，最终分数会加到大号上。<br/><div style="height:0;border-bottom:1px solid #ccc;margin:5px auto"></div>
                        扣分时，什么角色扣分，分数就记录在什么角色上，<br/>
                        最终保存的时候会自动扣除对应大号的分数，<br/>
                        如果小号需要额外消耗的分数要直接记录额外的数量。<br/>
                        比如：小号20分拍得装备，翻倍40分，应该在小号上登记40分
                    </div>
                    <el-button type="text" class="collapse-title-btn">计分规则看这里</el-button>
                </el-tooltip>
                <span style="padding: 0 20px;"></span>
                <el-select v-model="newPlayer" value-key="name" clearable filterable placeholder="请选择角色">
                    <el-option v-for="player in players"
                        :key="player.name"
                        :label="player.name"
                        :value="player">
                    </el-option>
                </el-select>
                <el-button type="primary" size="mini" @click="appendPlayer" :disabled="!canAddPlayer">增加参与人员</el-button>
            </div>
            <component ref="dkpPanel" :is="dkpMode=='byBoss'?'DkpByBoss':'DkpByItem'" :dkp-obj="dkpParsed"></component>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="beforeImportDialogClose" size="mini">取 消</el-button>
            <el-button type="primary" @click="doImport" size="mini">提 交</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getAllPlayerClasses, getRaidList, getRaidDetail, importDkpData, saveToFile } from "../service/api";
import RaidDetailNormal from "../components/RaidDetailNormal";
import RaidDetailTimeLine from "../components/RaidDetailTimeLine";
import DkpByBoss from "../components/DkpByBoss";
import DkpByItem from "../components/DkpByItem";

function dateFormat(v) {
  let dt = new Date(v);
  return (
    dt.getFullYear() +
    "-" +
    ("0" + (dt.getMonth() + 1)).slice(-2) +
    "-" +
    ("0" + dt.getDate()).slice(-2) +
    " " +
    ("0" + dt.getHours()).slice(-2) +
    ":" +
    ("0" + dt.getMinutes()).slice(-2) +
    ":" +
    ("0" + dt.getSeconds()).slice(-2)
  );
}

export default {
  components: { RaidDetailNormal, RaidDetailTimeLine, DkpByBoss, DkpByItem },
  data() {
    return {
      classMap: {
        战士: "#c2b396",
        盗贼: "#e4ff95",
        法师: "#4ee0ff",
        牧师: "#fbfbff",
        萨满祭司: "#f793d9",
        术士: "#6b75ee",
        德鲁伊: "#f99645",
        猎人: "#8ac37e"
      },
      tableData: { total: 0, list: [] },
      searchConditions: {
        zone: "",
        dateRange: [],
        pageNo: 1,
        pageSize: 10
      },
      raidDateOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      raidShow: false,
      raid: {
        key: "",
        start: "",
        end: "",
        players: [],
        boss: [],
        loot: []
      },
      raidSource: {},
      mode: "normal",
      importFormShow: false,
      formLabelWidth: "100px",
      charset: 'gbk',
      parsingCompleted: false,
      scoreType: 'TAQ',
      dkpMode: "byBoss",
      dkpStr: "",
      dkpParsed: {},
      newPlayer: null,
      players: []
    };
  },
  computed: {
    ...mapGetters(["isLogin", "token", 'level']),
    canAddPlayer() {
      return this.newPlayer;
    }
  },
  methods: {
    pageSizeChange(val) {
      this.fetchData(1, val);
    },
    pageNoChange(val) {
      this.fetchData(val, this.pageSize);
    },
    fetchData(pageNo = 1, pageSize = 10) {
      this.searchConditions.pageNo = pageNo;
      this.searchConditions.pageSize = pageSize;
      getRaidList({
        ...this.searchConditions
      }).then(({ data }) => {
        this.tableData = data.data;
      });
    },
    refreshData() {
      this.fetchData(
        this.searchConditions.pageNo,
        this.searchConditions.pageSize
      );
    },
    appendPlayer() {
      this.$refs.dkpPanel.appendPlayer(this.newPlayer);
    },
    viewDetail(key) {
      getRaidDetail({
        key
      }).then(({ data }) => {
        this.raid = data.data.raid;
        this.raidSource = data.data.source;
        this.$nextTick(_=>{
          this.raidShow = true;        
        })
      });
    },
    clearFiles () {
      this.$refs.upload.clearFiles()
    },
    showImportForm() {
      this.importFormShow = true;
    },
    uploadSuccess (res, file, fileList) {
      if(res.status!=0){
        this.$message.error(res.msg);
        return;
      }
      this.dkpParsed = res.data;
      this.dkpMode = res.data.mode;
      this.scoreType = ({
        '安其拉神殿': 'TAQ2',
        '纳克萨玛斯': 'NAXX2'
      }[res.data.zone])  || 'TAQ2'
      this.parsingCompleted = true;
    },
    confirmClose (done) {
      this.$confirm('确定要取消导入吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
      });
    },
    beforeImportDialogClose () {
      this.$confirm('确定要取消导入吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importFormShow = false;
      });
    },
    doImport () {
      if(!this.parsingCompleted){
        this.$alert('请先导入内容！')
        return;
      }

      this.$confirm('确定要导入吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        importDkpData({
          data: {
            ...this.$refs.dkpPanel.dkpRecord,
            ...this.dkpParsed,
            scoreType: this.scoreType
          }
        }).then(_=>{
          this.importFormShow = false;
          this.refreshData();
          this.$nextTick(_=>{
            this.parsingCompleted = false;
            this.$refs.upload.clearFiles();
            this.dkpParsed = {};
          })
        })
      }).catch(_=>{

      });
      // console.log({
      //       ...this.$refs.dkpPanel.dkpRecord,
      //       ...this.dkpParsed,
      //       scoreType: this.scoreType
      //     })
    },
    saveToFile () {
      this.$confirm('确定要保存数据到文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        saveToFile().then(_=>{
          this.$message.success('保存成功');
        })
      }).catch(_=>{
        
      })
    }
  },
  created() {
    this.fetchData();
    getAllPlayerClasses().then(({ data }) => {
      this.players = data.data.list;
    });
  }
};
</script>

<style lang="less" scoped>
.padding-tb {
  padding: 10px 0;
}
.raid-info-area{
  padding: 5px 0;
  margin-top: 5px;
}
.underline{
  border-bottom: 1px solid gray;
  padding-bottom: 2px;
}
.name-wrapper {
  display: flex;
  flex-wrap: wrap;
  .name-label {
    background: rgba(0, 0, 0, 0.7);
    line-height: 18px;
    width: 6.2em;
    padding: 0 5px;
    margin-right: 2px;
    margin-bottom: 2px;
    white-space: nowrap;
    border-radius: 4px;
    font-size: 12px;
  }
}
.collapse-title-wrapper {
  display: flex;
  width: 100%;
  .collapse-title {
    flex: 1;
    color: #409eff;
    font-weight: bold;
  }
  .collapse-title-btn {
    text-align: right;
  }
}
</style>

<style lang="less" scoped>
.import-dialog{
  display: flex;
  >.is-fullscreen{
    &.el-dialog{
      display: flex !important;
      flex-direction: column;
      >.el-dialog__body{
        flex:1;
        overflow: auto;
      }
    }
  }
}

.first-down-label{
  position: absolute;
  top: -4px;
  left: -40px;
  background: red;
  padding-top: 4px;
  color: white;
  font-weight: bolder;
  width: 100px;
  transform: rotate(-45deg);  
}
</style>

<style>
.el-table--border td{
  position: relative;
  overflow: hidden;
}  
</style>

